package com.bauer.java.springboot.simpleapp.service;

import com.bauer.java.springboot.simpleapp.dto.BaseResponse;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: weirui
 * @create: 2020-01-07 11:10
 **/
@Service
public class DemoService {

    private static Logger logger = LoggerFactory.getLogger(DemoService.class);


    @Async("testExecutor")
    public void test(int i) throws InterruptedException {
        Thread.sleep(5000);
        logger.info("hello {} number{}", Thread.currentThread().getName(), i);
    }

    /**
     *  参数配置详见
     * @see com.netflix.hystrix.HystrixCommandProperties
     * @return
     */

    @HystrixCommand(fallbackMethod = "fallBackTestHystrix", commandProperties = {
        //方法超时调用 回滚方法
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500"),
        //超时时是否中断线程
        @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "false"),

        //一个统计窗口中 至少有20次请求才生效
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
        //失败率超过50触发熔断
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),
        //统计窗口的时间
        @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")},

        threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "10"),
            @HystrixProperty(name = "maxQueueSize", value = "4000"),
            @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
            @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
            @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10")
        })
    public BaseResponse testHystrix() {
        long sleep = new Random().nextInt(1000);
        System.out.println(sleep);
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new BaseResponse(0, "成功", sleep);
    }

    public BaseResponse fallBackTestHystrix() {
        return new BaseResponse(999, "服务异常");
    }
}
